package com.consumer.handsome.utils;

import com.alibaba.fastjson.JSON;
import com.consumer.handsome.domain.dto.UserLoginDto;
import com.consumer.handsome.exception.BussinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Map;
import java.util.StringJoiner;

@Slf4j
public class HttpClientUtil {
    public String GetResponse(String url,Object objectDto) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<byte[]> exchange = null;
        String responseBody=null;
        try {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("Content-Type", "application/json");
            String string = JSON.toJSONString(objectDto);
            Map<String,String> map = JSON.parseObject(string, Map.class);
            log.info("params:---->"+map);
            log.info("header:---->"+ JSON.toJSONString(httpHeaders));
            StringJoiner queryString = new StringJoiner("&");
            map.forEach((key, value) ->queryString.add(key+ "=" +value));
            URI uri = new URI(url+"?"+queryString);
            log.info("uri"+uri);
            HttpEntity<LinkedMultiValueMap<String, String>> httpEntity = new HttpEntity(httpHeaders);
            HttpMethod httpMethod =HttpMethod.GET;
            exchange = restTemplate.exchange(uri,httpMethod,httpEntity,byte[].class);
             responseBody = new String(exchange.getBody());
        } catch (Exception e) {
            throw  new BussinessException("500","call api 失败");
        }
        return responseBody;
    }

    public static void main(String[] args) {
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        UserLoginDto userLoginDto = new UserLoginDto();
        userLoginDto.setPassword("asdas@qq.com");
        userLoginDto.setUsername("asdasdxcxzsa");
        String s = httpClientUtil.GetResponse("www.baidu.com", userLoginDto);
    }


}

